package com.starrin.trashtalk;

import javax.faces.context.FacesContext;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@WebFilter
public class LoginFilter implements Filter {

    /**
     * Checks if user is logged in. If not it redirects to the login.xhtml page.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Get the loginBean from session attribute
        HttpSession session = ((HttpServletRequest)request).getSession();
        LoginBean loginBean = (LoginBean) session.getAttribute("loginBean");

        // For the first application request there is no loginBean in the session so user needs to log in
        // For other requests loginBean is present but we need to check if user has logged in successfully
        if (loginBean == null || !loginBean.isLoggedIn ()) {
            String contextPath = ((HttpServletRequest)request).getContextPath();
            String requestURI = ((HttpServletRequest) request).getRequestURI();
            ((HttpServletResponse) response).sendRedirect(contextPath + "/login.xhtml?from=" + URLEncoder.encode(requestURI, "UTF-8"));
            return;
            //FacesContext.getCurrentInstance().getExternalContext().redirect(contextPath + "/login.xhtml?from=" + URLEncoder.encode(requestURI, "UTF-8"));
        }

        chain.doFilter(request, response);

    }

    public void init(FilterConfig config) throws ServletException {
        // Nothing to do here!
    }

    public void destroy() {
        // Nothing to do here!
    }

}
